﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;
using mvcForum.Core.Specifications;
using mvcForum.Web.Controllers;
using mvcForum.Web.ViewModels.Create;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAdmin.Controllers {

	public class ForumAccessController : ForumAdminBaseController {
		private readonly IRepository<Core.Forum> forumRepo;
		private readonly IRepository<ForumAccess> accessRepo;
		private readonly IRepository<Group> groupRepo;
		private readonly IRepository<AccessMask> masksRepo;

		public ForumAccessController(IWebUserProvider userProvider, IContext context)
			: base(userProvider, context) {

			this.forumRepo = this.GetRepository<Core.Forum>();
			this.accessRepo = this.GetRepository<ForumAccess>();
			this.groupRepo = this.GetRepository<Group>();
			this.masksRepo = this.GetRepository<AccessMask>();
		}

		[HttpPost]
		public ActionResult Update(Int32 id) {
			Core.Forum forum = this.forumRepo.Read(id);
			var forumAccess = this.accessRepo.ReadMany(new ForumAccessSpecifications.SpecificForum(forum));
			foreach (var access in forumAccess) {
				this.accessRepo.Delete(access);
			}
			this.Context.SaveChanges();

			IEnumerable<Group> groups = this.groupRepo.ReadAll().ToList();
			foreach (var group in groups) {
				string key = String.Format("Mask{0}", group.Id);
				int maskId;
				if (key.Length > 4 && !String.IsNullOrWhiteSpace(Request.Form[key]) && Int32.TryParse(Request.Form[key], out maskId)) {
					AccessMask accessMask = this.masksRepo.Read(maskId);
					ForumAccess access = new ForumAccess(forum, group, accessMask);
					this.accessRepo.Create(access);
					this.Context.SaveChanges();
				}
			}

			return RedirectToAction("Edit", "Forum", new RouteValueDictionary { { "id", forum.Id } });
		}
	}
}